package com.hope.hotel.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hope.hotel.config.AlipayConfig;
import com.hope.hotel.entity.po.Booking;
import com.hope.hotel.mapper.BookingMapper;
import com.hope.hotel.service.PaymentService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.slf4j.helpers.Reporter.info;

/**
 * 支付服务实现
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {

    private final AlipayConfig alipayConfig;
    private final BookingMapper bookingMapper;

    private static final String FORMAT = "json";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";

    /**
     * 创建支付订单
     */
    @Override
    @Transactional
    public void createPayment(String bookingId, HttpServletResponse response) throws AlipayApiException, IOException {
        // 查询预订信息
        Booking booking = bookingMapper.selectById(bookingId);
        if (booking == null) {
            log.info("预订消息不存在");
            throw new RuntimeException("预订信息不存在");
        }
        // 初始化配置
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 创建request 设计参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", bookingId);   // 订单号
        bizContent.put("total_amount", booking.getTotalPrice());  // 订单金额
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 支付方式
        bizContent.put("subject", "旅游订单");
        request.setBizContent(bizContent.toJSONString());
        request.setReturnUrl(alipayConfig.getReturnUrl());

        // 调用支付接口
        String result = null;
        try {
            result = alipayClient.pageExecute(request).getBody();  // 获取支付结果
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();
        System.out.println("沙箱支付展示订单展示，回调");
    }

    @Override
    public void notifyPayment(HttpServletRequest request) {
        try {
            if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
                System.out.println("支付宝成功回调");
                System.out.println("=========支付宝异步回调========");
                Map<String, String> params = new HashMap<>();
                Map<String, String[]> requestParams = request.getParameterMap();
                for (String name : requestParams.keySet()) {
                    params.put(name, request.getParameter(name));
                }

                String sign = params.get("sign");
                String content = AlipaySignature.getSignCheckContentV1(params);
                boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), CHARSET);

                if (checkSignature) {
                    // 验证通过
                    System.out.println("交易名称："  + params.get("subject"));
                    System.out.println("交易状态：" + params.get("trade_status"));
                    System.out.println("交易金额：" + params.get("total_amount"));
                    System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
                    System.out.println("订单号：" + params.get("out_trade_no"));
                    System.out.println("买家支付宝唯一id：" + params.get("buyer_id"));
                    System.out.println("买家付款时间：" + params.get("gmt_payment"));
                    System.out.println("买家付款金额："+  params.get("buyer_pay_amount"));

                    String orderUid = params.get("out_trade_no");
                    // 更新订单状态
                    bookingMapper.updateBookingStatus(orderUid);
                }




            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

} 